<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-alert title="注意：只允许为第三级分类设置相关参数！" :closable="false" type="warning" show-icon> </el-alert>
        </el-col>
      </el-row>
      <el-row class="choose">
        <el-col>
          选择商品分类:

          <el-cascader v-model="selectValue" :options="parentsCateList" :props="cascaderProps" @change="handleChange" clearable></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="this.selectValue.length !== 3" @click="addParmasDialogVisible = true">添加参数</el-button>
          <el-table :data="manyParamsList" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="removeTag(scope.row, index)">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="50px"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditorParamsDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="this.selectValue.length !== 3" @click="addParmasDialogVisible = true">添加属性</el-button>
          <el-table :data="onlyParamsList" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="removeTag(scope.row, index)">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="50px"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditorParamsDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog :title="'添加' + title" :visible.sync="addParmasDialogVisible" width="50%" @close="addParamsDialogClose">
      <el-form :model="addParamsForm" ref="addParamasFormRef" :rules="addParamasFormRules" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParmasDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParmas">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="'修改' + title" :visible.sync="editorParmasDialogVisible" width="50%">
      <el-form :model="editorParamsForm" ref="editorParamasFormRef" :rules="editorParamasFormRules" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="editorParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorParmasDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorParmas">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      selectValue: [],
      parentsCateList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      manyParamsList: [],
      onlyParamsList: [],
      addParamsForm: {
        attr_name: ''
      },
      addParamasFormRules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      addParmasDialogVisible: false,
      editorParmasDialogVisible: false,
      editorParamsForm: {
        attr_name: ''
      },
      editorParamasFormRules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      attr_id: ''
    }
  },

  components: {},
  created () {
    this.getParentsCateList()
  },
  computed: {
    title () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    id () {
      if (this.selectValue.length !== 3) {
        return null
      } else {
        return this.selectValue[this.selectValue.length - 1]
      }
    }
  },

  methods: {
    async getParentsCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类失败！')
      }
      this.parentsCateList = res.data
      console.log(res)
    },
    handleChange () {
      console.log(this.selectValue)
      this.getParamsList()
    },
    handleTabClick () {
      console.log(this.activeName)
      this.getParamsList()
    },
    async getParamsList () {
      const { data: res } = await this.$http.get(`categories/${this.selectValue[this.selectValue.length - 1]}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      res.data.forEach(item => {
        if (!item.attr_vals) {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(' ')
        }
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }
      if (this.activeName === 'many') {
        this.manyParamsList = res.data
      } else {
        this.onlyParamsList = res.data
      }
    },
    async addParmas () {
      const { data: res } = await this.$http.post(`categories/${this.id}/attributes`, {
        attr_name: this.addParamsForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 201) return this.$message.error('添加失败！')
      this.$message.success('添加成功！')
      this.getParamsList()
      this.addParmasDialogVisible = false
    },
    addParamsDialogClose () {
      this.$refs.addParamasFormRef.resetFields()
    },
    async showEditorParamsDialog (attrId) {
      const { data: res } = await this.$http.get(`categories/${this.id}/attributes/${attrId}`, {
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败！')
      this.editorParamsForm = res.data
      this.attr_id = attrId
      console.log(this.id)
      this.editorParmasDialogVisible = true
    },
    editorParmas () {
      this.$refs.editorParamasFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.id}/attributes/${this.attr_id}`, {
          attr_name: this.editorParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败！')
        }
        this.$message.success('修改参数成功！')
        this.getParamsList()
        this.editorParmasDialogVisible = false
      })
    },
    async removeParams (attrId) {
      const deleteConfirm = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(deleteConfirm);
      if (deleteConfirm !== 'confirm') {
        return this.$message.info('已取消删除该参数！')
      }
      const { data } = await this.$http.delete(`categories/${this.id}/attributes/${attrId}`)
      if (data.meta.status !== 200) {
        return this.$message.error('删除参数失败！')
      }
      this.$message.success('删除参数成功！')
      this.getParamsList()
    },
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      this.changeAttrVals(row)

      row.inputVisible = false
    },
    async changeAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('更新成功！')

      row.inputVisible = false
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async removeTag (row, index) {
      row.attr_vals.splice(index, 1)
      this.changeAttrVals(row)
    }
  }
}
</script>
<style scoped>
.choose {
  margin: 15px 0;
}
.el-cascader {
  width: 300px;
}
.el-tag {
  margin: 7px;
}
.input-new-tag {
  width: 130px;
}
</style>
